package com.algorithm.recursion_multi;

/**
 * 递归杨辉三角
 */
public class E03PascalTriangle {

    /**
     * 优化1: 使用二维数组记忆法
     *
     * @param triangle 二维数组
     * @param i        行坐标
     * @param j        列坐标
     * @return 该坐标元素值
     */
    private static int element(int[][] triangle, int i, int j) {
        if (triangle[i][j] > 0) {
            return triangle[i][j];
        }
        if (j == 0 || j == i) {
            triangle[i][j] = 1;
            return 1;
        }
        triangle[i][j] = element(triangle, i - 1, j - 1) + element(triangle, i - 1, j);
        return triangle[i][j];
    }

    private static void printSpace(int n, int i) {
        int num = (n - 1 - i) * 2;  //设置数字处于中间
        for (int j = 0; j < num; j++) {
            System.out.print(" ");
        }
    }

    public static void print(int n) {
        int[][] triangle = new int[n][];
        for (int i = 0; i < n; i++) { //行
            triangle[i] = new int[i + 1]; //第i行列的个数。添加列到对应的行
            printSpace(n, i);
            for (int j = 0; j <= i; j++) {
                System.out.printf("%-4d", element(triangle, i, j));
            }
            System.out.println();
        }
    }


    /**
     * 优化2: 使用一维数组记忆法
     *
     * @param row
     * @param i
     */
    private static void createRow(int[] row, int i) {
        if (i == 0) {
            row[0] = 1;
            return;
        }
        for (int j = i; j > 0; j--) {
            row[j] += row[j - 1];
        }
    }

    public static void print2(int n) {
        int[] row = new int[n];
        for (int i = 0; i < n; i++) { //行
            createRow(row, i);
            printSpace(n, i);
            for (int j = 0; j <= i; j++) {
                System.out.printf("%-4d", row[j]);
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
//        System.out.println(element(4, 2));
        System.out.println("------《二维数组记忆法》---------");
        print(5);
        System.out.println("----《一维数组记忆法》------");
        print2(5);
    }
}
